package com.example.activiti.config.inteceptor;

import com.example.activiti.common.MessageBody;
import com.example.activiti.config.UserLocal;
import com.example.activiti.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mr.yuan
 * @version v1.0
 * @date 2019/11/21 10:18
 **/
@Slf4j
@Component
public class WebInterceptor implements HandlerInterceptor {

    @Value("${jwt.token}")
    private String authorization;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(request.getRemoteHost(),request.getServletPath());
//        log.info("the request arrival,{},{}",request.getServletPath(),request.getRemoteHost());
        String token = request.getHeader(authorization);
        if (StringUtils.isBlank(token)) {
            response.getWriter().write(MessageBody.error("missing token identifier").toString());
            return false;
        }
        try {
            boolean result = JwtTokenUtils.verifyToken(token);
            if (!result) {
                response.getWriter().write(MessageBody.error("用户鉴权失败").toString());
                return false;
            }

        }catch (Exception e) {
            response.getWriter().write(MessageBody.error(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserLocal.clean();
        MDC.clear();
    }
}
